package cn.kailangtu.myapplication;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import cn.kailangtu.myapplication.data.CanDataManager;
import cn.kailangtu.myapplication.data.specialview.ElectricView;
import cn.kailangtu.myapplication.databinding.ActivityMainBinding;
import cn.kailangtu.myapplication.events.PageRefreshEvent;
import cn.kailangtu.myapplication.services.SerialDataService;
import cn.kailangtu.myapplication.services.Service_Rs485_1;
import cn.kailangtu.myapplication.tools.FomaterUtils;
import cn.kailangtu.serialport.ReceiveData;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import android.content.Intent;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

     //队列
    private LinkedBlockingQueue<ReceiveData> reportMsgQueue = new LinkedBlockingQueue<>();
    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

    private ImageView btnPage10Up,btnPage10Right,btnPage11Up,btnPage11Right,btnPage11Left;
    private ImageView btnPage20Left,btnPage20Up,btnPage20Right,btnPage21Up,btnPage21Right,btnPage21Left;
    private ImageView btnPage30Left,btnPage30Up,btnPage30Right,btnPage31Up,btnPage31Right,btnPage31Left;
    private ImageView btnPage40Left,btnPage40Up,btnPage40Right,btnPage41Up,btnPage41Left;
    private List<View> lsContainer = new ArrayList<>();
    private TextView btnPage00To10,btnPage00To20,btnPage00To30,btnPage00To40;
    private ImageView ivElectricTop1,ivElectricTop2,ivElectricTop3,ivElectricTop4,ivElectricTop5,ivElectricTop6,ivElectricTop7,ivElectricTop8,ivElectricTop9,ivElectricTop10,ivElectricTop11,ivElectricTop12;
    private Button btnClean里程;
    private TextView tv总里程;
    private ImageButton btnToMain;


    // private AutoMeterView autoMeterView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        hideNavigate();


        new Thread(new Runnable() {
            @Override
            public void run() {
                CanDataManager.getInstance().build(MainActivity.this);
            }
        }).start();

        EventBus.getDefault().register(this);

        initContainer();

        initView0();
        initComponent();
        initService();

        onMessageEvent(null);

        new Thread(new Runnable() {
            @Override
            public void run() {
                CanDataManager.getInstance().buildMain(MainActivity.this);
            }
        }).start();
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //EventBus  推出
        EventBus.getDefault().unregister(this);
        // 取消定时任务以防止内存泄漏

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PageRefreshEvent event){
        Log.d("MainActivity==>onMessageEvent","进入刷新了");
        if(binding.rlPage0.getVisibility() == View.VISIBLE)
        {
            Log.d("MainActivity==>onMessageEvent","进入刷新了，，rlPage0");
            CanDataManager.getInstance().RefreshView(R.id.llPage0,this);
            tv总里程.setText(CanDataManager.getInstance().get总里程());
        }
        else if(binding.rlPage10.getVisibility() == View.VISIBLE)
        {
            Log.d("MainActivity==>onMessageEvent","进入刷新了，，rlPage10");
            CanDataManager.getInstance().RefreshView(R.id.llPage10,this);
        }
        else if( binding.rlPage11.getVisibility() == View.VISIBLE )
        {
            Log.d("MainActivity==>onMessageEvent","进入刷新了，，rlPage11");
            CanDataManager.getInstance().RefreshView(R.id.llPage11,this);
        }
        else if( binding.rlPage20.getVisibility() == View.VISIBLE )
        {
            Log.d("MainActivity==>onMessageEvent","进入刷新了，，rlPage20");
            CanDataManager.getInstance().RefreshView(R.id.llPage20,this);
        }
        else if( binding.rlPage21.getVisibility() == View.VISIBLE )
        {
            Log.d("MainActivity==>onMessageEvent","进入刷新了，，rlPage21");
            CanDataManager.getInstance().RefreshView(R.id.llPage21,this);
        }
        else if( binding.rlPage30.getVisibility() == View.VISIBLE )
        {
            Log.d("MainActivity==>onMessageEvent","进入刷新了，，rlPage30");
            CanDataManager.getInstance().RefreshView(R.id.llPage30,this);
        }
        else if( binding.rlPage31.getVisibility() == View.VISIBLE )
        {
            Log.d("MainActivity==>onMessageEvent","进入刷新了，，rlPage31");
            CanDataManager.getInstance().RefreshView(R.id.llPage31,this);
        }
        else if( binding.rlPage40.getVisibility() == View.VISIBLE )
        {
            Log.d("MainActivity==>onMessageEvent","进入刷新了，，rlPage40");
            CanDataManager.getInstance().RefreshView(R.id.llPage40,this);
        }
        else if( binding.rlPage41.getVisibility() == View.VISIBLE )
        {
            Log.d("MainActivity==>onMessageEvent","进入刷新了，，rlPage41");
            CanDataManager.getInstance().RefreshView(R.id.llPage41,this);
        }


        List<Integer> ls时间控件 = CanDataManager.getInstance().getLs时间控件();
        for(Integer currentTextView : ls时间控件)
        {
            process时间控件(findViewById(currentTextView));
        }

    }


    Map<String,DateFormat> mapDateFormat = new HashMap<>();
    private void process时间控件(TextView tvTime)
    {
        if(tvTime.getTag() != null )
        {
            String formatString = tvTime.getTag().toString();
            if(formatString.indexOf("WEEK") > -1)
            {
                formatString = formatString.replace("WEEK", FomaterUtils.get星期());
            }

            if(mapDateFormat.containsKey(formatString))
            {
                tvTime.setText(mapDateFormat.get(formatString).format(new Date()));
            }
            else
            {
                DateFormat dateFormat = new SimpleDateFormat(formatString);
                mapDateFormat.put(formatString,dateFormat);
            }
        }
    }


    private void hideNavigate(){
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }

        getWindow().setStatusBarColor(Color.TRANSPARENT);// Color.TRANSPARENT = 0 表示#00000000即透明颜色
        getWindow().setNavigationBarColor(Color.TRANSPARENT);

        //隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    }

    /***
     * 初始化服务
     */
    private void initService()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(this, SerialDataService.class));
            startForegroundService(new Intent(this, Service_Rs485_1.class));
        } else {

            startService(new Intent(this, SerialDataService.class));
            startService(new Intent(this, Service_Rs485_1.class));
        }
    }

    /***
     * 初始化容器
     */
    private void initContainer()
    {
        lsContainer.add(binding.rlPage10);
        lsContainer.add(binding.rlPage11);
        lsContainer.add(binding.rlPage20);
        lsContainer.add(binding.rlPage21);
        lsContainer.add(binding.rlPage30);
        lsContainer.add(binding.rlPage31);
        lsContainer.add(binding.rlPage40);
        lsContainer.add(binding.rlPage41);
        lsContainer.add(binding.rlPage00);
        lsContainer.add(binding.rlPage0);

    }

    private void initView0()
    {
        tv总里程 = findViewById(R.id.tv总里程);
        ivElectricTop1 = findViewById(R.id.ivElectricTop1);
        ivElectricTop2 = findViewById(R.id.ivElectricTop2);
        ivElectricTop3 = findViewById(R.id.ivElectricTop3);
        ivElectricTop4 = findViewById(R.id.ivElectricTop4);
        ivElectricTop5 = findViewById(R.id.ivElectricTop5);
        ivElectricTop6 = findViewById(R.id.ivElectricTop6);
        ivElectricTop7 = findViewById(R.id.ivElectricTop7);
        ivElectricTop8 = findViewById(R.id.ivElectricTop8);
        ivElectricTop9 = findViewById(R.id.ivElectricTop9);
        ivElectricTop10 = findViewById(R.id.ivElectricTop10);
        ivElectricTop11 = findViewById(R.id.ivElectricTop11);
        ivElectricTop12 = findViewById(R.id.ivElectricTop12);
    }


    private void resetShowView(int showViewId)
    {

        if(showViewId == R.id.rlPage00)
        {
            initSubPage00();
        }
        else if(showViewId == R.id.rlPage10)
        {
            initSubPage10();
        }
        else if(showViewId == R.id.rlPage11)
        {
            initSubPage11();
        }
        else if(showViewId == R.id.rlPage20)
        {
            initSubPage20();
        }
        else if(showViewId == R.id.rlPage21)
        {
            initSubPage21();
        }
        else if(showViewId == R.id.rlPage30)
        {
            initSubPage30();
        }
        else if(showViewId == R.id.rlPage31)
        {
            initSubPage31();
        }
        else if(showViewId == R.id.rlPage40)
        {
            initSubPage40();
        }
        else if(showViewId == R.id.rlPage41)
        {
            initSubPage41();
        }

        for(View view : lsContainer){
            if(view.getId() == showViewId)
            {
                view.setVisibility(View.VISIBLE);
            }
            else
            {
                view.setVisibility(View.GONE);
            }
        }
    }

    boolean initPage00 = false;
    boolean initPage10 = false;
    boolean initPage11 = false;
    boolean initPage20 = false;
    boolean initPage21 = false;
    boolean initPage30 = false;
    boolean initPage31 = false;
    boolean initPage40 = false;
    boolean initPage41 = false;

    /***
     * 初始化特殊组件
     */
    private void initComponent()
    {
        ElectricView.getInstance().init(ivElectricTop1,ivElectricTop2,ivElectricTop3,ivElectricTop4,ivElectricTop5,ivElectricTop6,ivElectricTop7,ivElectricTop8,ivElectricTop9,ivElectricTop10,ivElectricTop11,ivElectricTop12);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btnPage00To10) {
            resetShowView(R.id.rlPage10);
        } else if (id == R.id.btnPage00To20) {
            resetShowView(R.id.rlPage20);
        } else if (id == R.id.btnPage00To30) {
            resetShowView(R.id.rlPage30);
        } else if (id == R.id.btnPage00To40) {
            resetShowView(R.id.rlPage40);
        } else if (id == R.id.btnPage10Up) {
            resetShowView(R.id.rlPage00);
        } else if (id == R.id.btnPage10Right) {
            resetShowView(R.id.rlPage11);
        } else if (id == R.id.btnPage11Up) {
            resetShowView(R.id.rlPage00);
        } else if (id == R.id.btnPage11Left) {
            resetShowView(R.id.rlPage10);
        } else if (id == R.id.btnPage11Right) {
            resetShowView(R.id.rlPage20);
        } else if (id == R.id.btnPage20Left) {
            resetShowView(R.id.rlPage11);
        } else if (id == R.id.btnPage20Right) {
            resetShowView(R.id.rlPage21);
        } else if (id == R.id.btnPage20Up) {
            resetShowView(R.id.rlPage00);
        } else if (id == R.id.btnPage21Left) {
            resetShowView(R.id.rlPage20);
        } else if (id == R.id.btnPage21Right) {
            resetShowView(R.id.rlPage30);
        } else if (id == R.id.btnPage21Up) {
            resetShowView(R.id.rlPage00);
        } else if (id == R.id.btnPage30Left) {
            resetShowView(R.id.rlPage21);
        } else if (id == R.id.btnPage30Right) {
            resetShowView(R.id.rlPage31);
        } else if (id == R.id.btnPage30Up) {
            resetShowView(R.id.rlPage00);
        } else if (id == R.id.btnPage31Left) {
            resetShowView(R.id.rlPage30);
        } else if (id == R.id.btnPage31Right) {
            resetShowView(R.id.rlPage40);
        } else if (id == R.id.btnPage31Up) {
            resetShowView(R.id.rlPage00);
        } else if (id == R.id.btnPage40Left) {
            resetShowView(R.id.rlPage31);
        } else if (id == R.id.btnPage40Right) {
            resetShowView(R.id.rlPage41);
        } else if (id == R.id.btnPage40Up) {
            resetShowView(R.id.rlPage00);
        } else if (id == R.id.btnPage41Left) {
            resetShowView(R.id.rlPage40);
        } else if (id == R.id.btnPage41Up) {
            resetShowView(R.id.rlPage00);
        } else if (id == R.id.btnClean里程) {
            Log.d("SHOOTLEE_CLICK","进来了");
           Dialog dialog = new AlertDialog.Builder(this)
                    .setTitle("删除确认")
                    .setMessage("确定要删除此项吗？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            CanDataManager.getInstance().clean清空里程();
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create();
            // 获取对话框的 Window 对象并设置全屏标志
            Window window = dialog.getWindow();
            if (window != null) {
                window.setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
                window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
                window.getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
            }
            dialog.show();
        }
        else if(id == R.id.btnToMain){
            resetShowView(R.id.rlPage0);
        }
    }


    public void clickToElectricView(View view) {
        resetShowView(R.id.rlPage00);
    }

    private void initSubPage00(){
        if(!initPage00) {
            initPage00 = true;
            LayoutInflater.from(MainActivity.this).inflate(R.layout.page_00, binding.rlPage00, true);
            btnPage00To10 = findViewById(R.id.btnPage00To10);
            btnPage00To20 = findViewById(R.id.btnPage00To20);
            btnPage00To30 = findViewById(R.id.btnPage00To30);
            btnPage00To40 = findViewById(R.id.btnPage00To40);
            btnToMain = findViewById(R.id.btnToMain);
            btnClean里程 = findViewById(R.id.btnClean里程);

            btnPage00To10.setOnClickListener(this);
            btnPage00To20.setOnClickListener(this);
            btnPage00To30.setOnClickListener(this);
            btnPage00To40.setOnClickListener(this);
            btnClean里程.setOnClickListener(this);
            btnToMain.setOnClickListener(this);
        }
    }
    private void initSubPage10(){
        if(!initPage10)
        {
            initPage10 = true;
            LayoutInflater.from(MainActivity.this).inflate(R.layout.page_10, binding.rlPage10, true);
            CanDataManager.getInstance().addNewControler(this,R.id.llPage10);


            btnPage10Up = findViewById(R.id.btnPage10Up);
            btnPage10Right = findViewById(R.id.btnPage10Right);
            btnPage10Right.setOnClickListener(this);
            btnPage10Up.setOnClickListener(this);
        }
    }
    private void initSubPage11(){
        if(!initPage11) {
            initPage11 = true;
            LayoutInflater.from(MainActivity.this).inflate(R.layout.page_11, binding.rlPage11, true);
            CanDataManager.getInstance().addNewControler(this,R.id.llPage11);
            btnPage11Left = findViewById(R.id.btnPage11Left);
            btnPage11Right = findViewById(R.id.btnPage11Right);
            btnPage11Up = findViewById(R.id.btnPage11Up);
            btnPage11Left.setOnClickListener(this);
            btnPage11Right.setOnClickListener(this);
            btnPage11Up.setOnClickListener(this);
        }
    }
    private void initSubPage20(){
        if(!initPage20) {
            initPage20 = true;
            LayoutInflater.from(MainActivity.this).inflate(R.layout.page_20, binding.rlPage20, true);
            CanDataManager.getInstance().addNewControler(this,R.id.llPage20);
            btnPage20Left = findViewById(R.id.btnPage20Left);
            btnPage20Right = findViewById(R.id.btnPage20Right);
            btnPage20Up = findViewById(R.id.btnPage20Up);
            btnPage20Left.setOnClickListener(this);
            btnPage20Right.setOnClickListener(this);
            btnPage20Up.setOnClickListener(this);
        }
    }
    private void initSubPage21(){
        if(!initPage21) {
            initPage21 = true;
            LayoutInflater.from(MainActivity.this).inflate(R.layout.page_21, binding.rlPage21, true);
            CanDataManager.getInstance().addNewControler(this,R.id.llPage21);
            btnPage21Left = findViewById(R.id.btnPage21Left);
            btnPage21Right = findViewById(R.id.btnPage21Right);
            btnPage21Up = findViewById(R.id.btnPage21Up);
            btnPage21Left.setOnClickListener(this);
            btnPage21Right.setOnClickListener(this);
            btnPage21Up.setOnClickListener(this);
        }
    }
    private void initSubPage30(){
        if(!initPage30) {
            initPage30 = true;
            LayoutInflater.from(MainActivity.this).inflate(R.layout.page_30, binding.rlPage30, true);
            CanDataManager.getInstance().addNewControler(this,R.id.llPage30);
            btnPage30Left = findViewById(R.id.btnPage30Left);
            btnPage30Right = findViewById(R.id.btnPage30Right);
            btnPage30Up = findViewById(R.id.btnPage30Up);
            btnPage30Left.setOnClickListener(this);
            btnPage30Right.setOnClickListener(this);
            btnPage30Up.setOnClickListener(this);
        }
    }
    private void initSubPage31(){
        if(!initPage31) {
            initPage31 = true;
            LayoutInflater.from(MainActivity.this).inflate(R.layout.page_31, binding.rlPage31, true);
            CanDataManager.getInstance().addNewControler(this,R.id.llPage31);
            btnPage31Left = findViewById(R.id.btnPage31Left);
            btnPage31Right = findViewById(R.id.btnPage31Right);
            btnPage31Up = findViewById(R.id.btnPage31Up);
            btnPage31Left.setOnClickListener(this);
            btnPage31Right.setOnClickListener(this);
            btnPage31Up.setOnClickListener(this);
        }
    }
    private void initSubPage40(){
        if(!initPage40) {
            initPage40 = true;
            LayoutInflater.from(MainActivity.this).inflate(R.layout.page_40, binding.rlPage40, true);
            CanDataManager.getInstance().addNewControler(this,R.id.llPage40);
            btnPage40Left = findViewById(R.id.btnPage40Left);
            btnPage40Right = findViewById(R.id.btnPage40Right);
            btnPage40Up = findViewById(R.id.btnPage40Up);
            btnPage40Left.setOnClickListener(this);
            btnPage40Right.setOnClickListener(this);
            btnPage40Up.setOnClickListener(this);
        }
    }
    private void initSubPage41(){

        if(!initPage41) {
            initPage41 = true;
            LayoutInflater.from(MainActivity.this).inflate(R.layout.page_41, binding.rlPage41, true);
            CanDataManager.getInstance().addNewControler(this,R.id.llPage41);
            btnPage41Left = findViewById(R.id.btnPage41Left);
            btnPage41Up = findViewById(R.id.btnPage41Up);

            btnPage41Left.setOnClickListener(this);
            btnPage41Up.setOnClickListener(this);

        }
    }
}